#include "ZeroEntity.h"

#include <cstdlib>

ZeroEntity::ZeroEntity()
{
	mScore = 0;
	mGeneCount = 0;
	mGene = NULL;
	mProtein = NULL;
	mIsTranslated = false;
}

ZeroEntity::ZeroEntity(ZeroGene **gene, int geneCount)
{
	mScore = 0;
	mGeneCount = geneCount;
	mGene = gene;
	mProtein = NULL;
	mIsTranslated = false;
}

ZeroEntity::~ZeroEntity()
{
	if (mGene) {
		for (int i = 0;i < mGeneCount;i++)
			if (mGene[i])
				delete mGene[i];
		delete [] mGene;
	}
	if (mProtein) {
		for (int i = 0;i < mGeneCount;i++)
			if (mProtein[i])
				delete mProtein[i];
		delete [] mProtein;
	}
}

void ZeroEntity::setScore(int score)
{
	mScore = score;
}

int ZeroEntity::getScore()
{
	return mScore;
}

int ZeroEntity::getGeneCount()
{
	return mGeneCount;
}

ZeroGene* ZeroEntity::getGene(int index)
{
	return mGene[index];
}

bool ZeroEntity::setGene(int index, ZeroGene *gene)
{
	if (index < mGeneCount) {
		mGene[index] = gene;
		return true;
	}
	return false;
}

ZeroEntity* ZeroEntity::mate(ZeroEntity *entity)
{
	ZeroGene **newGene = new ZeroGene* [mGeneCount];
	for (int i = 0;i < mGeneCount;i++)
		newGene[i] = mGene[i]->crossover(entity->getGene(i));
	return new ZeroEntity(newGene, mGeneCount);
}

ZeroEntity* ZeroEntity::copy()
{
	ZeroGene **newGene = new ZeroGene* [mGeneCount];
	for (int i = 0;i < mGeneCount;i++)
		newGene[i] = mGene[i]->copy();
	return new ZeroEntity(newGene, mGeneCount);
}

ZeroEntity* ZeroEntity::RandomEntity(int geneCount)
{
	ZeroGene **newGene = new ZeroGene* [geneCount];
	for (int i = 0;i < geneCount;i++)
		newGene[i] = ZeroGene::RandomGene();
	return new ZeroEntity(newGene, geneCount);
}

bool ZeroEntity::translate()
{
	mIsTranslated = false;
	if (mProtein) {
		for (int i = 0;i < mGeneCount;i++)
			delete mProtein[i];
		delete [] mProtein;
	}
	mProtein = new ZeroProtein* [mGeneCount];
	for (int i = 0;i < mGeneCount;i++) {
		mProtein[i] = ZeroProtein::Translate(mGene[i]);
		if (!mProtein[i])
			return false;
	}
	mIsTranslated = true;
	return true;
}

ZeroProtein* ZeroEntity::getProtein(int index)
{
	if (index >= mGeneCount)
		return NULL;
	if (!mIsTranslated)
		return NULL;
	return mProtein[index];
}

